import 'package:gate_cli/models/res_config.dart';
import 'package:gate_cli/utils/json_command_util.dart';
import 'package:gate_cli/utils/string_extension.dart';

class JsonType {
  String? name;
  String? value;
  JsonType? subType;
  JsonClz? subClz;

  String? get formatValue {
    return value?.formatAssetName();
  }

  JsonType({this.name, this.subType, this.subClz, this.value});

  factory JsonType.fromDynamic(String key, dynamic d, ResJson resJson) {
    final type = JsonCommandUtil.getType(d);
    if (type == 'List') {
      List<dynamic> list = d;
      if (list.isNotEmpty) {
        final first = list.first;
        return JsonType(name: type, subType: JsonType.fromDynamic(key, first, resJson), value: key);
      } else {
        return JsonType(name: null);
      }
    }
    if (type == 'Class') {
      Map<String, dynamic> map = d;
      return JsonType(name: type, subClz: JsonClz.fromMap(key, map, resJson), value: key);
    }
    return JsonType(name: type, subType: null, value: key);
  }
}

class JsonClz {
  String _clzName;
  List<JsonType> attributes;
  ResJson resJson;

  JsonClz(this._clzName, {required this.resJson, this.attributes = const []});

  String get clzName {
    return _clzName.formatClassName(checkKey: true);
  }

  String get fileName {
    return _clzName.formatFileName();
  }

  factory JsonClz.fromMap(String name, Map<String, dynamic> maps, ResJson resJson) {
    final clzName = name.isEmpty ? 'Entity' : name;
    if (maps.isNotEmpty) {
      final attrs = maps.entries.map((e) => JsonType.fromDynamic(e.key, e.value, resJson)).toList();
      return JsonClz(clzName, resJson: resJson, attributes: attrs);
    }
    return JsonClz(clzName, resJson: resJson);
  }
}
